package com.yanqu.road.dao.impl.servercenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.servercenter.ServerAutoOpenConfig;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServerAutoOpenConfigDaoImpl extends TempDao {

    public static String getServerAutoOpenConfigSql = "select * from `t_s_auto_open_config`";
    public Map<Integer, ServerAutoOpenConfig> getServerAutoOpenConfig() {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, ServerAutoOpenConfig> map = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(getServerAutoOpenConfigSql);
            rs = call.executeQuery();
            while (rs.next()) {
                ServerAutoOpenConfig data = parseData(rs);
                map.put(data.getChannelId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);} finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }


    public static String insertServerAutoOpenConfigSql = "REPLACE into `t_s_auto_open_config`(channelId,type,level,areaSplitFlow) values (?,?,?,?)";
    public boolean updateData(ServerAutoOpenConfig serverAutoOpenConfig) {
        getDb().setConnName(DbNameStrategy.getServerDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.INTEGER, serverAutoOpenConfig.getChannelId()));
        para.put(i++, new DbParameter(Types.INTEGER, serverAutoOpenConfig.getType()));
        para.put(i++, new DbParameter(Types.INTEGER, serverAutoOpenConfig.getLevel()));
        para.put(i++, new DbParameter(Types.VARCHAR, serverAutoOpenConfig.getAreaSplitFlow()));
        if (getDb().executeNoneQuery(insertServerAutoOpenConfigSql, para) > 0) {
            return true;
        }
        return false;

    }

    protected ServerAutoOpenConfig parseData(ResultSet rs) throws SQLException {
        ServerAutoOpenConfig serverAutoOpenConfig = new ServerAutoOpenConfig();
        serverAutoOpenConfig.setChannelId(rs.getInt("channelId"));
        serverAutoOpenConfig.setType(rs.getInt("type"));
        serverAutoOpenConfig.setLevel(rs.getInt("level"));
        serverAutoOpenConfig.setAreaSplitFlow(rs.getString("areaSplitFlow"));
        serverAutoOpenConfig.parseAreaSplitFlow();
        return serverAutoOpenConfig;
    }

}
